import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken } from '@/utils/auth'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 如果响应不是200，说明出错了
    if (response.status !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      
      if (response.status === 401) {
        // token过期，尝试使用refresh token
        const refreshToken = getRefreshToken()
        if (refreshToken) {
          store.dispatch('user/refreshToken', refreshToken).catch(() => {
            store.dispatch('user/resetToken')
            router.push(`/login?redirect=${router.currentRoute.fullPath}`)
          })
        } else {
          store.dispatch('user/resetToken')
          router.push(`/login?redirect=${router.currentRoute.fullPath}`)
        }
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service 